import cv2
import os
import subprocess
from flask import Response, jsonify

# 全局变量，存储当前使用的摄像头索引
current_camera_index = 0
video_devices = []
camera = None

def scan_cameras():
    global video_devices
    """扫描本机可用的摄像头"""
    video_devices = []
    available_cameras = []
    # 扫描 /dev/v4l/by-path/ 目录
    for dev in os.listdir('/dev/v4l/by-path'):
        if "bcm2835" in dev:
            continue
        elif "codec" in dev:
            continue
        else:
            video_devices.append(f'/dev/v4l/by-path/{dev}')
            
    for index, dev in enumerate(video_devices):
        try:
            # 尝试打开设备
            # device_path = f'/dev/v4l/by-id/{dev}'
            cap = cv2.VideoCapture(dev)
            if cap.isOpened():
                available_cameras.append({"index": index, "path": os.readlink(dev), "name": dev})  # 添加 index 属性
        except Exception as e:
            print(f"Error accessing {dev}: {e}")
        finally:
            cap.release()
    return available_cameras

def get_camera_details(camera_index):
    """获取摄像头的详细信息"""
    details = {}
    try:
        result = subprocess.run(['v4l2-ctl', '--device', f'/dev/video{camera_index}', '--all'],
                                capture_output=True, text=True, check=True)
        details['info'] = result.stdout
    except subprocess.CalledProcessError as e:
        details['error'] = str(e)
    return details

def generate_frames(camera_index):
    """生成实时视频流帧"""
    global camera, video_devices
    if camera is not None:
        camera.release()
    camera = cv2.VideoCapture(video_devices[camera_index])  # 使用传入的 camera_index
    while True:
        success, frame = camera.read()
        if not success:
            break
        else:
            # 将帧转换为 JPEG 格式
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
    if camera is not None:
        camera.release()

def capture_image():
    """捕获当前摄像头的一帧图像"""
    global current_camera_index, camera, video_devices
    if camera is None:
        camera = cv2.VideoCapture(video_devices[current_camera_index])
    success, frame = camera.read()
    if not success:
        return jsonify({"error": "Failed to capture image"}), 500

    # 将帧转换为 JPEG 格式
    ret, buffer = cv2.imencode('.jpg', frame)
    if not ret:
        return jsonify({"error": "Failed to encode image"}), 500

    # 返回图像
    return Response(buffer.tobytes(), mimetype='image/jpeg')

def set_camera(camera_index):
    """设置当前使用的摄像头"""
    global current_camera_index, camera, video_devices
    current_camera_index = camera_index
    if camera is not None:
        camera.release()
    camera = cv2.VideoCapture(current_camera_index)
    return jsonify({"status": "success", "camera_index": current_camera_index})

def close_camera():
    """关闭当前摄像头"""
    global camera
    if camera is not None:
        camera.release()
        camera = None
    return jsonify({"status": "closed"})